package com.wang.transfer.util.algorithm;

/**
 * 排列硬币
 */
public class ArrangeCoin {

    public static void main(String[] args) {
//        System.out.println(arrangeCoin(10));
        System.out.println(arrangeCoin2(5));
    }

    // 迭代
    public static int arrangeCoin(int n) {
        for (int i = 1; i <= n; i++) {
            n = n - i;
            if (n <= i) {
                return i;
            }
        }
        return 0;
    }

    public static int arrangeCoin2(int n) {
        int low = 0, high = n;
        while (low <= high) {
            int mid = (high - low) / 2 + low;
            int cost = ((mid + 1) * mid) / 2;
            if (cost == n) {
                return mid;
            } else if (cost > n) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return high;
    }
}
